package cn.pegasus.teamwork.advertisement.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.iyizhan.teamwork.base.controller.BaseController;
import cn.iyizhan.teamwork.base.util.FileHelper;
import cn.iyizhan.teamwork.base.util.ParameterEunm;
import cn.iyizhan.teamwork.base.util.ReMessage;
import cn.iyizhan.teamwork.base.util.UUIDGenerator;
import cn.iyizhan.teamwork.base.util.file.FtpUtils;
import cn.iyizhan.teamwork.base.util.plist.Icon;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("/upload/*")
public class ImageController extends BaseController<Object,Object>{
	Logger logger = Logger.getLogger(this.getClass());
	
    
    @RequestMapping(value = "/uploadFiles.do")  
    public void uploadFiles(@RequestParam(value = "Img1", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response /*, ModelMap model*/) throws Exception {  
        
        common(file,response,request); 
    }
    
    @RequestMapping(value = "/upload2Files.do")  
    public void upload2Files(@RequestParam(value = "Img2", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response /*, ModelMap model*/) throws Exception {  
        
        common(file,response,request); 
    }
    
    @RequestMapping(value = "/upload3Files.do")  
    public void upload3Files(@RequestParam(value = "Img3", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response /*, ModelMap model*/) throws Exception {  
        
        common(file,response,request); 
    } 

    @RequestMapping(value = "/upload4Files.do")  
    public void upload4Files(@RequestParam(value = "Img4", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response /*, ModelMap model*/) throws Exception {  
        
        common(file,response,request); 
    } 
    
    /**
     * 单文件上传
     * @param file
     * @param response
     * @throws Exception
     */
    private void common(MultipartFile file,HttpServletResponse response,HttpServletRequest request) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw = null;
        try {
            Map<String, Object> resultMap=new HashMap<>();
            String path = request.getSession().getServletContext().getRealPath("/");  
            String fileName = file.getOriginalFilename();  
            File targetFile = new File(path, fileName);  
            if(!targetFile.exists()){  
                targetFile.mkdirs();  
            }  
            //保存  
            file.transferTo(targetFile); 
            String original = file.getOriginalFilename();
            int index = original.lastIndexOf(".");
            String indexStr =  original.substring(index);
            String url = FtpUtils.uploadFile(UUID.randomUUID().toString()+indexStr,targetFile);
            resultMap.put("url", url);
            resultMap.put("status","success");
            resultMap.put("size",file.getSize()/1024);
            String jsonText = JSON.toJSONString(resultMap, true);
            if(null!=targetFile && targetFile.exists()){
            	targetFile.delete();
            }
            pw =response.getWriter();
            pw.write(jsonText);
            pw.flush();
        } finally {
            if(null!=pw){
                pw.close();
            }
        }
       
    }
    
    @RequestMapping(value = "/showImag")
    public void getImage(HttpServletRequest request,HttpServletResponse response) {
//        FileInputStream fis = null;
        HttpURLConnection httpConn = null;
        InputStream httpIn = null;
        OutputStream out = null;
        response.setContentType("image/gif");
        try {
            out = response.getOutputStream();
            System.out.println(request.getParameter("url"));
            URL remoteFile = new URL(request.getParameter("url"));
            httpConn = (HttpURLConnection)remoteFile.openConnection();  
            httpConn.setRequestProperty("User-Agent","Mozilla/4.0");   
//            response.setContentType("application/json;charset=UTF-8");
              
           
            httpIn = httpConn.getInputStream();
            byte[] b = new byte[4*1024];
            int readLength;
            while ((readLength = httpIn.read(b)) != -1) {   
                out.write(b, 0, readLength);  
                
            }
            out.flush();
        } catch (Exception e) {
             e.printStackTrace();
        } finally {
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (httpIn != null) {
                try {
                    httpIn.close();
                } catch (IOException e) {
                e.printStackTrace();
            }   
              }
        }
    }
    /**
     * 生成随机验证码
     * @throws IOException 
     */
    @RequestMapping(value = "/validationCode")
    public void generatorValidCode(HttpServletRequest request,HttpServletResponse response) throws IOException{
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        int width = 60, height = 20;
        BufferedImage image = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        Random random = new Random();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
          int x = random.nextInt(width);
          int y = random.nextInt(height);
          int xl = random.nextInt(12);
          int yl = random.nextInt(12);
          g.drawLine(x, y, x + xl, y + yl);
        }
        String sRand = "";
        for (int i = 0; i < 4; i++) {
          //String rand = String.valueOf(random.nextInt(10));
          String rand = getRandomChar();
          sRand += rand;
          g.setColor(new Color(20 + random.nextInt(110), 20 + random
              .nextInt(110), 20 + random.nextInt(110)));
          g.drawString(rand, 13 * i + 6, 16);
        }
        // 将认证码存入SESSION 
        HttpSession session = getSession();
        session.setAttribute("rand", sRand);
        g.dispose();
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
    
    private String getRandomChar()
    {    
       //产生小于2的随机数并进行四舍五入
       int rand = (int)Math.round(Math.random() * 2);
       long itmp = 0;
       char ctmp = '\u0000';
        switch (rand)
       {
            case 1:
               //产生65-90的Ascii
               itmp = Math.round(Math.random() * 25 + 65);
               //强制转化为char，获取相应的大写字母
                ctmp = (char)itmp;
               //下面有了return就可以省略break
                return String.valueOf(ctmp);            
           case 2:
                //获取97-122的Ascii，获取小写字母
                itmp = Math.round(Math.random() * 25 + 97);
               ctmp = (char)itmp;
                return String.valueOf(ctmp);
           default :
               //获取数字
               itmp = Math.round(Math.random() * 9);
                return String.valueOf(itmp);
       }
  }
    
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255)
          fc = 255;
        if (bc > 255)
          bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
    
    /** 
     * 根据byte数组，生成文件 
     */  
    public static File getFile(byte[] bfile, String filePath,String fileName) {  
        BufferedOutputStream bos = null;  
        FileOutputStream fos = null;  
        File file = null;  
        try {  
            File dir = new File(filePath);  
            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在  
                dir.mkdirs();  
            }  
            file = new File(filePath+"\\"+fileName);  
            fos = new FileOutputStream(file);  
            bos = new BufferedOutputStream(fos);  
            bos.write(bfile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (bos != null) {  
                try {  
                    bos.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
            if (fos != null) {  
                try {  
                    fos.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
        }  
        return file;
    }  
    
    /**
     * 
     * @Title: uoloadApk
     * @Description: 上传APK方法
     * @param file 文件流对象
     * @param request
     * @return 上传后的结果 iconPath:apkICO的地址 path:apk上传地址 appName:APK 名称
     */
    protected Map<String, Object> uoloadApk(MultipartFile file, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, String> uploadResult = new HashMap<>();
        if (file != null && !file.isEmpty()) {

            String fileName = file.getOriginalFilename();
            String abc = new UUIDGenerator().generate().toString();
            String fileType = fileName.substring(fileName.lastIndexOf("."));

            // 服务器默认地址
            String myappPath = request.getSession().getServletContext().getRealPath("/");

            FileOutputStream outStream = null;
            InputStream input = null;
            InputStream fis = null;
            try {
                long size = file.getSize();
                byte[] data = new byte[(int) size];
                input = file.getInputStream();
                input.read(data);
                byte[] arrays = file.getBytes();
                File f = getFile(arrays, "c:", file.getOriginalFilename());
                String original = f.getName();
                int index = original.lastIndexOf(".");
                String indexStr =  original.substring(index);
                String path = FtpUtils.uploadFile(UUID.randomUUID().toString()+indexStr,f);
                if (StringUtils.isNoneBlank(path)) {
                    // 创建一个临时目录
                    File outFile = new File(myappPath + File.separator + abc + fileType);
                    if (!outFile.exists()) {
                        outFile.createNewFile();
                    }
                    outStream = new FileOutputStream(outFile);
                    outStream.write(data);
                    String temp_path = outFile.getCanonicalPath();

                    // 解析出来APK的icon
                    Map<String, String> apkMap = Icon.getParams(temp_path, myappPath + File.separator + "icon");
                    if (apkMap != null && !apkMap.isEmpty()) {
                        String temp_iconPath = apkMap.get(Icon.APP_ICON);
                        fis = new FileInputStream(temp_iconPath);
                        File iconFile = new File(temp_iconPath);
                        // 上传icon
                        String iconFileName = iconFile.getName();
                        int iconIndex = iconFileName.lastIndexOf(".");
                        String iconIndexStr =  iconFileName.substring(iconIndex);
                        String iconPath = FtpUtils.uploadFile(UUID.randomUUID().toString()+iconIndexStr,iconFile);
                        // 删除本地缓存的文件
                        FileHelper.getInstance().deleteFile(temp_path);
                        FileHelper.getInstance().deleteFile(temp_iconPath);
                        // 保存上传结果
                        uploadResult.putAll(apkMap);
                        uploadResult.put("iconPath", iconPath);
                        uploadResult.put("apkSize", String.valueOf(size));
                    }
                    //删除临时生成的文件
                    if(null!=f && f.exists()){
                    	f.delete();
                    }
                    uploadResult.put("path", path);
                    resultMap = ReMessage.resultBack(ParameterEunm.SUCCESSFUL_CODE, uploadResult);
                }else{
                    resultMap = ReMessage.resultBack(ParameterEunm.ERROR_UPLOADFILE_CODE, "上传APK出错");
                }
                
            } catch (IOException e) {
                resultMap = ReMessage.resultBack(ParameterEunm.ERROR_UPLOADFILE_CODE, "上传出错");
                logger.error("Request server error! ", e);
            } catch (Exception e) {
                resultMap = ReMessage.resultBack(ParameterEunm.ERROR_UPLOADFILE_CODE, "上传出错");
                logger.error("Request server error! ", e);
            } finally {
                try {
                    if (null != fis) {
                        fis.close();
                    }
                    outStream.close();
                    input.close();
                } catch (Exception e) {
                	logger.error("Request server error!", e);
                }
            }
        } else {
            resultMap = ReMessage.resultBack(ParameterEunm.ERROR_UPLOADFILE_CODE, "上传出错");
        }
        return resultMap;
    }
}
